<template>
  <div>
    <!-- 评价 -->
    <el-table-form ref="form" :model="query">
      <el-form-item label="责任机构:">
        <el-tree-select
          v-model="query.orgId"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item label="处理人:" prop="userId">
        <el-select v-model="query.userId" :loading="$loadingPlugin.getOwnersList" clearable filterable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评分时间:" :table-form-merge="1.5">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" :loading="$loadingPlugin.fetchData" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="2" :loading="$loadingPlugin.exportFile" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      v-loading="$loadingPlugin.fetchData"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
  </div>
</template>

<script>
  import { parseTime } from '@/utils'
  import moment from 'dayjs'
  import { queryEvaluateManageList, queryExportEvaluateList, queryOwnersList } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  export default {
    name: 'evaluateManage',
    data() {
      return {
        treeData: [],
        ownersList: [],
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          orgId: '',
          userId: ''
        },
        searchParams: {},
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'orderCode',
              label: '关联单号',
              width: 120
            },
            {
              prop: 'csmName',
              label: '联系人'
            },
            {
              prop: 'phoneNumber',
              label: '联系电话',
              width: 110
            },
            {
              prop: 'contactAddress',
              label: '联系地址',
              width: 200
            },
            {
              prop: 'orgName',
              label: '责任机构',
              width: 110
            },
            {
              prop: 'userName',
              label: '处理人'
            },
            {
              prop: 'goodsEvaluation',
              label: '商品评价',
              width: 110,
              formatter: row => this.formatter(row.goodsEvaluation)
            },
            {
              prop: 'orgEvaluation',
              label: '服务评价',
              width: 110,
              formatter: row => this.formatter(row.orgEvaluation)
            },
            // {
            //   prop: 'userEvaluation',
            //   label: '送气工评价',
            //   width: 110,
            //   formatter: row => this.formatter(row.userEvaluation)
            // },
            {
              prop: 'createUser',
              label: '评价用户'
            },
            {
              prop: 'evaluationStr',
              label: '评价内容',
              width: 200
            },
            {
              prop: 'createTime',
              label: '评价时间',
              width: 180,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'exportDomain'
      ])
    },
    created() {
      this.getTreeData()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.startDate = this.date[0]
          query.endDate = this.date[1]
        }
        if (this.query.orgId) {
          const org = this.orgList.find(item => item.orgId === this.query.orgId)
          query.orgSNNo = org.orgSNNo
          query.orgName = org.orgName
        }
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 366) {
          this.$message.error('评分时间最大支持查询1年')
          return
        }
        const res = await queryEvaluateManageList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.$set(this.query, 'userId', '')
        this.getOwnersList(value.orgId)
      },
      closeTree(v) {
        this.$set(this.query, 'userId', '')
        this.ownersList = []
      },
      // 查询处理人列表
      async getOwnersList(org) {
        const res = await queryOwnersList({
          orgId: org || -1
        })
        this.ownersList = res.data
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          // copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportEvaluateList({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      formatter(value) {
        return value || value === 0 ? value + '星' : ''
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
